var util = require('../../utils/util')
var api = require('../../config/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //隐患等级
    hiddenLevelItem: [
      { value: 0, name: '一般问题' },
      { value: 1, name: '一般隐患' },
      { value: 2, name: '较大隐患' },
      { value: 3, name: '重大隐患' },

    ],
    hiddenLevelIndex: null,
    report: {},

    //选择分配的业务部门
    selectedOrg: {},
    selectedOrgindex: null,

    //选择分管领导
    selectedCharge: {},
    selectedChargeindex: null,

    //选择主要领导
    selectedMain: {},
    selectedMainindex: null,

    //已经选择的业务部门
    rectificationOrgId: {},
    //已经选择的分管领导
    chargeLeader:{},
    //已经选择的主要领导
    mainLeader:{},


    //今天日期
    rectificationPeriod: '',
    //奖励金额
    suggestionRewards: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    const eventChannel = this.getOpenerEventChannel()
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('row', function (data) {
      console.log(data)
      that.setData({
        report: data,
        ['reportInfo.hiddenLevel']:0,
        imgList: (data.fliePath || '').split(';').filter(item => item !== ''),
        imgListed: (data.verifyImage || '').split(';').filter(item => item !== '')
      })

    })

    // 初始化或从服务器获取数据
    this.initOrgData();
    this.initChargeData();
    this.initMainData();
    //初始今天日期
    this.getToday();


  },

  //浏览图片
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  //浏览核实照片
  ViewImageed(e) {
    wx.previewImage({
      urls: this.data.imgListed,
      current: e.currentTarget.dataset.url
    });
  },

  checkPhone(event) {
    let row = event.currentTarget.dataset.data;
    wx.makePhoneCall({
      phoneNumber: row,
      success: function (res) {
        console.log(res)
      },
      fail: function (err) {
        console.log(err)
      }
    })
  },

  bindPickerChange(event) {
    let index = event.detail.value;
    this.data.report.hiddenLevel = this.data.hiddenLevelItem[index].value
    this.setData({
      hiddenLevelIndex: index
    })
    
  },



  //进度条
  loadModal() {
    this.setData({
      loadModal: true
    })
  },
  closeModal() {
    this.setData({
      loadModal: false
    })
  },


  //-------------------------初始数据 部门人员-----------------//
  //业务部门
  initOrgData() {
    let that = this
    var dataReq = { category: 'DEPT', depth: 2 }
    
    util.request(api.getOrgIdlistByCategoryAndDepth, JSON.stringify(dataReq), 'POST').then(function (res) {
    
      if (res.code === "200") {
        that.setData({
          selectedOrg: res.data

        })

      } else {
        util.showErrorToast(res.message);

      }

    }).catch((err) => {
      console.log("登录远程服务器catch:" + err);
      //reject(err);
    });
  },

  //分管领导
  initChargeData(){
    let that = this
    var roleCode = { roleCodeList: ['role_charge_leader'] }
    util.request(api.getVerifyUserlist, JSON.stringify(roleCode), 'POST').then(function (res) {
      
      if (res.code === "200") {
        that.setData({
          selectedCharge: res.data
        })

      } else {
        util.showErrorToast(res.message);

      }

    }).catch((err) => {
      console.log("登录远程服务器catch:" + err);
      //reject(err);
    });

  },

  //获取主要灵动
  initMainData(){
    let that = this
    var roleCode = { roleCodeList: ['role_main_leader'] }
    util.request(api.getVerifyUserlist, JSON.stringify(roleCode), 'POST').then(function (res) {
      
      if (res.code === "200") {
        that.setData({
          selectedMain: res.data
        })

      } else {
        util.showErrorToast(res.message);

      }

    }).catch((err) => {
      console.log("登录远程服务器catch:" + err);
      //reject(err);
    });

  },

  //业务部门分配
  bindPickerChangeOrg(event) {
    let index = event.detail.value;
    this.data.rectificationOrgId = this.data.selectedOrg[index]
    this.setData({
      selectedOrgindex: index
    })
  },
  //分管领导
  bindPickerChargeOrg(event) {
    let index = event.detail.value;
    this.data.chargeLeader = this.data.selectedCharge[index]
    this.setData({
      selectedChargeindex: index
    })
  },
  //主要领导
  bindPickerMainOrg(event) {
    let index = event.detail.value;
    this.data.mainLeader = this.data.selectedMain[index]
    this.setData({
      selectedMainindex: index
    })
  },
  //日期选择
  DateChange(e) {
    this.setData({
      rectificationPeriod: e.detail.value
    })
  },
  //输入金额
  bindinputRewards(e) {
    this.setData({
      suggestionRewards: e.detail.value
    })
  },


  //-------------------------初始数据 部门人员-----------------//

  //保存提交
  save() {
    console.log()
    if (this.data.report.hiddenLevel === '' || this.data.report.hiddenLevel == null) {
      util.showErrorToast('请选择隐患等级！');
      return false
    }
    if (Object.keys(this.data.chargeLeader).length <= 0 && (this.data.report.hiddenLevel ===2 || this.data.report.hiddenLevel ===3)) {
      util.showErrorToast('分管领导不能为空！');
      return false
    }
    if (Object.keys(this.data.mainLeader).length <= 0 &&  (this.data.report.hiddenLevel ===2 || this.data.report.hiddenLevel ===3)) {
      util.showErrorToast('主要领导不能为空！');
      return false
    }
    if (Object.keys(this.data.rectificationOrgId).length <= 0 && this.data.report.hiddenLevel !=0) {
      util.showErrorToast('业务部门不能为空！');
      return false
    }
    // if (this.data.rectificationPeriod === '' || this.data.rectificationPeriod == null) {
    //   util.showErrorToast('整改期限不能为空！');
    //   return false
    // }
    if (this.data.suggestionRewards === '' || this.data.suggestionRewards === 0) {
      util.showErrorToast('填写奖励金额！');
      return false
    }

    
    //提交上报数据
    let dataup = {
      reportId: this.data.report.reportId,
      hiddenLevel: this.data.report.hiddenLevel,
      suggestionRewards: this.data.suggestionRewards,
      rectificationOrgId: this.data.rectificationOrgId.id,
      rectificationOrgName: this.data.rectificationOrgId.name,
      rectificationPeriod: this.data.rectificationPeriod,
      chargeLeaderId:this.data.chargeLeader.id,
      chargeLeaderName:this.data.chargeLeader.name,
      mainLeaderId:this.data.mainLeader.id,
      mainLeaderName:this.data.mainLeader.name
    };
    let that = this;
    console.log(JSON.stringify(dataup))
    that.loadModal();
    util.request(api.mgrAudit, JSON.stringify(dataup), 'POST').then(function (res) {
      console.log(res)
      if (res.code == '200') {
        that.closeModal();
        //刷新界面
        console.log("========")
        wx.navigateBack()

      } else {
        util.showErrorToast(res.message);
        that.closeModal();
      }

    }).catch((err) => {
      that.closeModal();
      console.log("登录远程服务器catch:" + err);
      //reject(err);
    });


  },

  //获取今天的日期YYYY-MM-DD格式
  getToday() {
    const today = new Date();

    // 格式化为 YYYY-MM-DD
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');

    const todayStr = `${year}-${month}-${day}`;
    this.setData({
      rectificationPeriod:todayStr
    })

  }

})